﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.EditPages
{
    public partial class EditBrand : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if (!IsPostBack)
            {
                BrandList = Brands.LoadAllActiveBrands();
                Utilities.LoadListbox(lstBrand, BrandList.DefaultView, Brands.ColumnNames.BrandName, Brands.ColumnNames.ID);

                if(Branches.CurrentBranchID != SessionUser.BranchID || !SessionUser.Admin)
                {
                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnDelete.Enabled = false;
                    btnAdd.OnClientClick = "";
                    btnEdit.OnClientClick = "";
                    btnDelete.OnClientClick= "";
                }
            }
        }

        public Brands BrandList
        {
            get { return Session[BrandsKey] == null ? null : (Brands)Session[BrandsKey]; }
            set { Session[BrandsKey] = value; }
        }

        public string BrandsKey
        {
            get
            {
                if (ViewState["BrandsKey"] == null)
                    ViewState["BrandsKey"] = Guid.NewGuid().ToString();
                return ViewState["BrandsKey"].ToString();
            }
        }

        public string GetEditBrandNamePageLink()
        {
            return this.ResolveClientUrl("~/EditPages/EditBrandName.aspx?key=" + BrandsKey);
        }

        public void RefreshList()
        {
            BrandList.Filter = Brands.ColumnNames.Deleted + " = 0";
            Utilities.LoadListbox(lstBrand, BrandList.DefaultView, Brands.ColumnNames.BrandName, Brands.ColumnNames.ID);
        }

        protected void btnAddBrand_OnClick(Object sender, EventArgs e)
        {
            RefreshList();
        }

        protected void btnDeleteBrand_OnClick(Object sender, EventArgs e)
        {
            if(lstBrand.SelectedIndex < 0)
                return;

            if(!Brands.IsBrandInUse(int.Parse(lstBrand.SelectedValue)))
            {
                string oldFilter = BrandList.Filter;
                BrandList.Filter = Brands.ColumnNames.ID + "=" + lstBrand.SelectedValue;
                BrandList.Deleted = true;
                BrandList.LastModifiedByUser = SessionUser.ID;
                BrandList.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                BrandList.Save();
                BrandList.Filter = oldFilter;
                RefreshList();
            }
            else
            {
                ((Popup)Master).ShowErrorMessage("Brand " + lstBrand.SelectedItem.Text + " is in use. Can not delete!");
            }
        }
    }
}